package security.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author cyt
 * @create 2020-07-17 10:55
 */

@Slf4j
@RestController
public class LoginController {

    @RequestMapping("/success")
    public String success() {
        return "success";
    }

    @RequestMapping("/test")
    public String test() {
        return "test => " + getUsername();
    }

    @RequestMapping("/test/cyt")
    public String test2() {
        return "test cyt => " + getUsername();
    }

    @RequestMapping("/cyt")
    public String cyt() {
        return "cyt =>" + getUsername();
    }

    @RequestMapping("/cyt/test")
    public String cyt2() {
        return "cyt  test =>" + getUsername();
    }

    /**
     * 得到用户名
     *
     * @return
     */
    private String getUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        log.info("authentication=> " + authentication.toString());
        if (!authentication.isAuthenticated()) {
            return null;
        }
        Object principal = authentication.getPrincipal();
        log.info("principal=> " + principal.toString());
        String name = null;
        if (principal instanceof UserDetails) {
            name = ((UserDetails) principal).getUsername();
        } else {
            name = principal.toString();
        }
        return name;
    }

}
